package com.zzr.zzrbackend.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzr.zzrbackend.exception.ErrorException;
import com.zzr.zzrbackend.mapper.UserMapper;
import com.zzr.zzrbackend.pojo.domain.User;
import com.zzr.zzrbackend.pojo.dto.resultEnum.ResultEnum;
import com.zzr.zzrbackend.util.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtInterceptor extends InterceptorRegistry implements HandlerInterceptor {

    @Resource
    UserMapper userMapper;

    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object object) throws Exception{

        //获取token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ErrorException("没有token，重新登陆");
        }

        //获取token的userid
        String userName;
        try {
            //解密获取
            Claims claimsFromJwt = TokenUtils.getClaimsFromJwt(token);
            if (claimsFromJwt == null) {
                httpServletResponse.setCharacterEncoding("utf-8");
                httpServletResponse.setStatus(200);
                Map<Object, Object> map = new HashMap<>();
                map.put("code", ResultEnum.TOKEN_OVERDUE.getCode());
                map.put("message", ResultEnum.TOKEN_OVERDUE.getMessage());
                map.put("operation", "TOKEN验证未通过，请检查TOKEN");
                String jsonMap = new ObjectMapper().writeValueAsString(map);
                httpServletResponse.getWriter().write(jsonMap);
                return false;
            }
            userName = (String) claimsFromJwt.get("userName");
//            userName = JWT.decode(token).getAudience().get(0); //得到token中的userid载荷
        } catch (JWTDecodeException j) {
            return false;
        }

        //根据userid查询数据库
        User user = userMapper.selectByUserName(userName);

        if(user == null){
            throw new ErrorException("token验证失败，重新登陆");
        }

        try {
            TokenUtils.verify(token);
        } catch (Exception e) {
            throw new ErrorException(e.getMessage());
        }
        return true;
    }

    public Integer getUserId(HttpServletRequest httpServletRequest) {
        //获取token
        String token = httpServletRequest.getHeader("token");
        Claims claimsFromJwt = TokenUtils.getClaimsFromJwt(token);
        String userName = (String) claimsFromJwt.get("userName");
        //根据userid查询数据库
        User user = userMapper.selectByUserName(userName);
        return user.getId();
    }

    public Integer getUserId(String token) {
        //获取token
        Claims claimsFromJwt = TokenUtils.getClaimsFromJwt(token);
        String userName = (String) claimsFromJwt.get("userName");
        //根据userid查询数据库
        User user = userMapper.selectByUserName(userName);
        return user.getId();
    }
}
